<template>
    <div class="userManagement">
        <!--<ul class="search-bar">
            <li class="form-item">
                <p class="item-title">姓名:</p>
                <el-input size="small" v-model="params.realName" placeholder="请输入产品名称"/>
            </li>
            <li class="form-item">
                <p class="item-title">手机号:</p>
                <el-input size="small" v-model="params.mobilephone" placeholder="请输入产品编号"/>
            </li>
            <li class="form-item">
                <el-button type="primary" size="small" @click="handleSearch">查询</el-button>
                <el-button class="rest-btn" size="small" @click="handleReset">重置</el-button>
            </li>
        </ul>-->
        <div class="button-group">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="add" v-if="buttons[$buttonCode.add]">添加</el-button>
            <el-button type="danger" size="small" icon="el-icon-delete" @click="delChecked" v-if="buttons[$buttonCode.del]">删除</el-button>
        </div>
        <el-table :data="list" stripe ref="table" @selection-change="selectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="用户ID" width="100"></el-table-column>
            <el-table-column prop="userName" label="登录帐号"></el-table-column>
            <el-table-column prop="realName" label="真实姓名"></el-table-column>
            <el-table-column prop="mobilephone" label="手机号"></el-table-column>
            <el-table-column label="状态" width="160">
                <template #default="{row}">
                    <el-switch
                        :disabled="!buttons[$buttonCode.updateState]"
                        v-model="row.status"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="0"
                        @change="updateState(row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="创建时间">
                <template #default="{row}">
                    {{$formatDate(row.createTime)}}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="{row}">
                    <template v-if="row.id !== -1">
                        <el-button type="text" size="small" @click="edit(row)" v-if="buttons[$buttonCode.update]">编辑</el-button>
                        <el-button type="text" size="small" @click="del(row)" v-if="buttons[$buttonCode.del]">删除</el-button>
                        <el-button type="text" size="small" @click="resetPassword(row)" v-if="buttons[$buttonCode.restPassword]">重置密码</el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            :current-page="page"
            :page-size="$pageSize"
            layout="prev, pager, next"
            :total="total"
            @current-change="goPage"
        ></el-pagination>
        <el-dialog :visible.sync="editVisible" :title="isEdit ? '编辑用户' : '添加用户'">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-form">
                <el-form-item label="登录账号：" prop="userName">
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label="登录密码：" prop="password" v-if="!isEdit">
                    <el-input v-model="form.password"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名：" prop="realName">
                    <el-input v-model="form.realName"></el-input>
                </el-form-item>
                <el-form-item label="手机号：" prop="mobilephone">
                    <el-input v-model="form.mobilephone"></el-input>
                </el-form-item>
                <el-form-item label="角色：" prop="roleIds">
                    <el-checkbox v-model="form.roleIds" v-for="role of roleList" :label="role.id" :key="role.id">
                        {{role.name}}
                    </el-checkbox>
                </el-form-item>
                <el-form-item label="状态：" prop="name">
                    <el-switch
                        v-model="form.status"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="0"
                    ></el-switch>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button size="small" type="primary" :disabled="btnDisabled" @click="save">保存</el-button>
                <el-button size="small" @click="editVisible = false">取消</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {
    getUserList,
    updateUserState,
    resetUserPassword,
    delUser,
    updateUser,
    getRoleList,
} from '@/api/user';
import {regexp} from '@/common/utils/tool';
import mixin from '@/mixins/buttons';

export default {
    name: 'userList',
    mixins: [mixin],
    data() {
        return {
            params: {
                realName: '',
                mobilephone: '',
            },
            query: {},
            checkedId: [],
            list: [],
            page: 1,
            total: 0,
            editVisible: false,
            isEdit: false,
            roleList: [],
            form: {
                userName: '',
                password: '',
                realName: '',
                mobilephone: '',
                roleIds: [],
                status: 1,
                remarks: '',
            },
            rules: {
                userName: [
                    {required: true, message: '请输入登录帐号', trigger: 'blur'},
                ],
                password: [
                    {required: true, message: '请输入登录密码', trigger: 'blur'},
                ],
                realName: [
                    {required: true, message: '请输入真实姓名', trigger: 'blur'},
                ],
                mobilephone: [
                    {required: true, message: '请输入手机号', trigger: 'blur'},
                    {pattern: regexp.tel, message: '手机号格式错误', trigger: 'blur'},
                ],
            },
            btnDisabled: false,
        };
    },
    created() {
        this.getUserList();
        this.getRoleList();
    },
    methods: {
        getUserList() {
            getUserList({
                currentPage: this.page,
                pageSize: this.$pageSize,
            }).then(({data}) => {
                const {list, totalCount} = data;
                this.list = list.map(item => {
                    item.state = !!item.status;
                    return item;
                });
                this.total = totalCount;
            }).catch(err => {
                this.list = [];
                this.total = 0;
            });
        },
        // 分页切换
        goPage(page) {
            this.page = page;
            this.getUserList();
        },
        // 搜索
        handleSearch() {
            this.query = {...this.params};
            this.page = 1;
            this.getUserList();
        },
        // 重置搜索
        handleReset() {
            this.params = {
                realName: '',
                mobilephone: '',
            };
            this.handleSearch();
        },
        // 修改状态
        updateState(item) {
            const {id, status} = item;
            updateUserState({id, status}).then(() => {
                this.$message.success(`${status === 1 ? '启用' : '禁用'}用户成功`);
            }).catch(err => {
                item.status = status === 1 ? 0 : 1;
            });
        },
        // 获取角色列表
        getRoleList() {
            getRoleList().then(({data}) => {
                this.roleList = data.list;
            }).catch(err => {
                this.roleList = [];
            });
        },
        // 添加
        add() {
            this.isEdit = false;
            this.form = {
                userName: '',
                password: '',
                realName: '',
                mobilephone: '',
                roleIds: [],
                status: 1,
                remarks: '',
            };
            this.editVisible = true;
        },
        // 编辑
        edit(item) {
            this.isEdit = true;
            const {id, userName, realName, roleIds, mobilephone, status, remarks} = item;
            this.form = {id, userName, realName, mobilephone, status, remarks, roleIds};
            this.editVisible = true;
        },
        // 保存
        save() {
            this.$refs.form.validate((valid) => {
                if (!valid) {
                    return;
                }
                this.btnDisabled = true;
                updateUser(this.form).then(() => {
                    this.$message.success('保存成功');
                    this.btnDisabled = false;
                    this.getRoleList();
                    this.editVisible = false;
                }).catch(err => {
                    this.btnDisabled = false;
                });
            });
        },
        // 删除单个用户
        async del(item) {
            const {id, realName} = item;
            try {
                await this.$confirm(`确定要删除用户 ${realName} 吗?`);
                this.delUser([id]);
            } catch (e) {
                console.log(e);
            }
        },
        // 删除用户
        delUser(ids = []) {
            delUser({
                itemIds: ids,
            }).then(() => {
                this.$message.success('删除成功');
                if (this.list.length === ids.length && this.page > 1) {
                    this.page--;
                }
                this.getUserList();
            }).catch(err => {
                console.log(err);
            });
        },
        // 选择用户
        selectionChange(val) {
            this.checkedId = val.map(item => item.id);
        },
        // 批量删除
        async delChecked() {
            try {
                await this.$confirm(`确定要删除所选用户吗`);
                this.delUser(this.checkedId);
            } catch (e) {
                console.log(e);
            }
        },
        // 重置密码
        async resetPassword(item) {
            const {id, realName} = item;
            try {
                await this.$confirm(`确定要将用户 ${realName} 的密码重置为初始密码吗?`);
                await resetUserPassword({id});
                this.$message.success('重置密码成功');
            } catch (e) {
                console.log(e);
            }
        },
    },
};
</script>

<style scoped lang="less">

</style>
